<?php
require_once dirname(__FILE__) . '/OAuthPHP/library/OAuthRequester.php';

define( 'CONSUMER_KEY', '396370e2bd0f4c00c490340a9408208404d6e5f22' );
define( 'CONSUMER_SECRET', '8583bda88ac89fb804ff1aac1bb80380' );
define( 'CALLBACK_URI', 'oob' );
define( 'USER_ID', 3 );

$options = array(
    'consumer_key' => CONSUMER_KEY,
    'consumer_secret' => CONSUMER_SECRET,
    'server_uri' => 'http://api.qa.kinobaza.tv/',
    'signature_methods' => array( 'HMAC-SHA1', 'PLAINTEXT' ),
    'request_token_uri' => 'http://api.qa.kinobaza.tv/auth/request-token',
    'authorize_uri' => 'http://api.qa.kinobaza.tv/auth/authorize',
    'access_token_uri' => 'http://api.qa.kinobaza.tv/auth/access-token'
);
$store   = OAuthStore::instance( 'Session', $options );

$token = OAuthRequester::requestRequestToken( CONSUMER_KEY, USER_ID );

if ( !empty( $token[ 'authorize_uri' ] ) ) {
    if (strpos($token['authorize_uri'], '?')) {
        $uri = $token['authorize_uri'] . '&';
    } else {
        $uri = $token['authorize_uri'] . '?';
    }
    $uri .= 'oauth_token='.rawurlencode($token['token']).'&oauth_callback='.rawurlencode($callback_uri);

    echo "Перейдите по ссылке, чтобы авторизовать приложение (10 секунд у вас есть): " . $uri . "\n";

}

for ( $i = 10; $i >= 0; $i-- ) {
    echo "Осталось $i секунд\n";
    sleep( 1 );
}

try {
    OAuthRequester::requestAccessToken( CONSUMER_KEY, $token[ 'token' ], USER_ID);

} catch ( OAuthException $e ) {

}

$filepath = "/tmp/Pi_[rutracker.org]_DVO.avi";

$fp = fopen( $filepath, 'r' );
rewind( $fp );
$filepart = fread( $fp, 1024 * 1024 );
$hash = sha1( $filepart );
fclose( $fp );


$params = array( 'hash' => $hash, 'filepath' => $filepath );
$req = new OAuthRequester( 'http://api.qa.kinobaza.tv/films/search-by-file', 'GET', $params);
$result = $req->doRequest( USER_ID );

echo "\n\n\n";
var_dump( $result );


$film = json_decode( $result[ 'body' ] );
if ( !empty( $film ) ) {
    $params = array( 'status' => 'seen', 'id' => $film->id );
    $req = new OAuthRequester( 'http://api.qa.kinobaza.tv/my/films/set-status', 'POST', $params);
    $result = $req->doRequest( USER_ID );

    echo "\n\n\n";
    var_dump( $result );
}
